package com.phenix.share.demo

import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.selection.toggleable
import androidx.compose.material3.Button
import androidx.compose.material3.Checkbox
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.core.view.doOnAttach
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.viewmodel.compose.viewModel
import com.phenix.share.demo.ui.theme.DemoTheme
import com.phenix.share.superwindow.ISuperFloatingWindowCreator
import com.phenix.share.superwindow.SuperFloatingWindowManager

class MainActivity : ComponentActivity() {

    companion object {
        private const val TAG = "MainActivity"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d(TAG, "#onCreate...")
        enableEdgeToEdge()
        setContent {
            DemoTheme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    Greeting(
                        name = "Android",
                        modifier = Modifier.padding(innerPadding)
                    )
                }
            }
        }
    }

    override fun onStart() {
        super.onStart()
        Log.d(TAG, "#onStart...")
    }

    override fun onResume() {
        super.onResume()
        Log.d(TAG, "#onResume...")
    }

    override fun onPause() {
        super.onPause()
        Log.d(TAG, "#onPause...")
    }

    override fun onStop() {
        super.onStop()
        Log.d(TAG, "#onStop...${SuperFloatingWindowManager.getInstance().dump()}")
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG, "#onDestroy...")
    }
}

@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
    val vm: MainViewModel = viewModel()
    val ctx = LocalContext.current

    val TAG = "#MainActivty.Geeting"

    val autoAttachToEdgesState by vm.autoAttachToEdges.collectAsState()
    val showOnConnectedState by vm.showOnConnected.collectAsState()
    val draggableState by vm.draggable.collectAsState()


    DisposableEffect(Unit) {
        Log.d(TAG, "#Greeting.DisposableEffect")

        val lifecycleOwner = ctx as LifecycleOwner
        val observer = LifecycleEventObserver { _, event ->
            when (event) {
                Lifecycle.Event.ON_START -> {
                    println("App 进入前台")
                }

                Lifecycle.Event.ON_STOP -> {
                    println("App 进入后台")
                }

                else -> {}
            }
        }

        lifecycleOwner.lifecycle.addObserver(observer)

        SuperFloatingWindowManager.getInstance()
            .initialize(
                ctx.applicationContext,
                object : ISuperFloatingWindowCreator {
                    override fun createContentView(): View =
                        createView()
//                        createComposeView()

                    private fun createComposeView(): ComposeView {
                        val composeView = ComposeView(ctx).apply {
//                            doOnAttach {
                                setContent {
//                                    DemoTheme {
                                        Surface(
                                            modifier = Modifier.fillMaxSize(),
                                            color = MaterialTheme.colorScheme.background
                                        ) {
                                            Greeting("Android")
                                        }
//                                    }
//                                }
                            }
                        }
                        return composeView
                    }

                    private fun createView(): View = LayoutInflater.from(ctx.applicationContext)
                        .inflate(R.layout.layout_super_floating_window, null, false)
                        .apply {
                            findViewById<View>(R.id.button).setOnClickListener {
                                Toast.makeText(
                                    ctx,
                                    "您点击了SuperFloatingWindow的按钮!",
                                    Toast.LENGTH_LONG
                                ).show()
                            }
                        }

                    override fun gravity(): Int {
                        return Gravity.CENTER
                    }

                    override fun autoAttachToEdges(): Boolean {
                        return vm.autoAttachToEdges.value
                    }

                    override fun showOnConnected(): Boolean {
                        return vm.showOnConnected.value
                    }

                    override fun isDraggable(): Boolean {
                        return draggableState
                    }

                })

        onDispose {
            Log.d(TAG, "#Greeting.onDispose")
            SuperFloatingWindowManager.getInstance().release()
            lifecycleOwner.lifecycle.removeObserver(observer)
        }
    }
    Column {
        Text(
            text = "Hello $name!",
            modifier = modifier
        )

        Column {

            Row(
                Modifier
                    .fillMaxWidth()
                    .height(56.dp)
                    .toggleable(
                        value = autoAttachToEdgesState,
                        onValueChange = { vm.toggleAutoAttachToEdges() },
                        role = Role.Checkbox
                    )
                    .padding(horizontal = 16.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Checkbox(
                    checked = autoAttachToEdgesState,
                    onCheckedChange = null // null recommended for accessibility with screenreaders
                )
                Text(
                    text = "Auto Attach To Edges",
                    style = MaterialTheme.typography.bodyLarge,
                    modifier = Modifier.padding(start = 16.dp)
                )
            }
            Row(
                Modifier
                    .fillMaxWidth()
                    .height(56.dp)
                    .toggleable(
                        value = showOnConnectedState,
                        onValueChange = { vm.toggleShowOnConnected() },
                        role = Role.Checkbox
                    )
                    .padding(horizontal = 16.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Checkbox(
                    checked = showOnConnectedState,
                    onCheckedChange = null
                )
                Text(
                    text = "Show On Connected State",
                    style = MaterialTheme.typography.bodyLarge,
                    modifier = Modifier.padding(start = 16.dp)
                )
            }
            Row(
                Modifier
                    .fillMaxWidth()
                    .height(56.dp)
                    .toggleable(
                        value = draggableState,
                        onValueChange = { vm.toggleDraggable() },
                        role = Role.Checkbox
                    )
                    .padding(horizontal = 16.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Checkbox(
                    checked = draggableState,
                    onCheckedChange = null
                )
                Text(
                    text = "Draggable",
                    style = MaterialTheme.typography.bodyLarge,
                    modifier = Modifier.padding(start = 16.dp)
                )
            }
        }

        Button(onClick = {
            SuperFloatingWindowManager.getInstance().show()
        }) {
            Text(
                text = "showWindow",
                modifier = modifier
            )
        }
        Button(onClick = {
            SuperFloatingWindowManager.getInstance().hide()
        }) {
            Text(
                text = "hideWindow",
                modifier = modifier
            )
        }

        Button(onClick = {
            SuperFloatingWindowManager.getInstance().miniSize()
        }) {
            Text(
                text = "miniWindow",
                modifier = modifier
            )
        }
        Button(onClick = {
            SuperFloatingWindowManager.getInstance().restoreSize()
        }) {
            Text(
                text = "restoreWindow",
                modifier = modifier
            )
        }

        Button(onClick = {
            with(SuperFloatingWindowManager.getInstance()) {
                requestFocus(!isWindowFocused())
            }
        }) {
            Text(
                text = "requestFocus",
                modifier = modifier
            )
        }
    }
}

@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    DemoTheme {
        Greeting("Android")
    }
}